package com.dream.myqiyi.service.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import android.util.Log;

import com.dream.myqiyi.service.GenericManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus;
import com.j256.ormlite.dao.GenericRawResults;

public class GenericManagerImpl<T, PK extends Serializable> implements GenericManager<T, PK> {
	/**
     * Log variable for all child classes. Uses LogFactory.getLog(getClass()) from Commons Logging
     */
    //protected final Log log = LogFactory.getLog(getClass());

    /**
     * GenericDao instance, set by constructor of this class
     */
    protected Dao<T, PK> genericDao;

    /**
     * Public constructor for creating a new GenericManagerImpl.
     * @param genericDao the GenericDao to use for persistence
     */
    public GenericManagerImpl(final Dao<T, PK> genericDao) {
        this.genericDao = genericDao;
    }

    /**
     * {@inheritDoc}
     */
    public List<T> getAll() {
        try {
			return genericDao.queryForAll();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public T get(PK id) {
        try {
			return genericDao.queryForId(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public boolean exists(PK id) {
        try {
			return genericDao.idExists(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public T save(T object) {
        try {
			CreateOrUpdateStatus status = genericDao.createOrUpdate(object);
			if (status.isCreated()) {
				return object;
			}
			if (status.isUpdated()) {
				return object;
			}
			return null;
		} catch (SQLException e) {
			Log.e("[mynote]", e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }

    public void update(T object) {
        try {
			genericDao.update(object);
		} catch (SQLException e) {
			Log.e("[mynote]", e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    /**
     * {@inheritDoc}
     */
    public void remove(PK id) {
        try {
			genericDao.deleteById(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public GenericRawResults<String[]> queryRaw(String query, String... arguments) {
    	try {
			return genericDao.queryRaw(query, arguments);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
}
